import Vue from 'vue'
import VueI18n from 'vue-i18n'
import moment from 'moment'
import store from '@/store' // Vuex

import enUS from './lang/en-US'
import ptBR from './lang/pt-BR'
import zhCN from './lang/zh-CN'
import zhTW from './lang/zh-TW'

Vue.use(VueI18n)


const messages = {
  'en-US': { ...enUS },
  'pt-BR': { ...ptBR },
  'zh-CN': { ...zhCN },
  'zh-TW': { ...zhTW },
}

const i18n = new VueI18n({
  silentTranslationWarn: true,
  locale: store.getters.lang,
  fallbackLocale: store.getters.lang,
  messages
})

const loadedLanguages = [store.getters.lang]

function setI18nLanguage(lang) {
  i18n.locale = lang
  document.querySelector('html').setAttribute('lang', lang)
  return lang
}

export function loadLanguageAsync(lang) {
  return new Promise(resolve => {
    if (i18n.locale !== lang) {
      if (!loadedLanguages.includes(lang)) {
        if (!lang) return;
        return import(`./lang/${lang}`).then(msg => {
          const locale = msg.default
          i18n.setLocaleMessage(lang, locale)
          loadedLanguages.push(lang)
          moment.updateLocale(locale.momentName, locale.momentLocale)
          return setI18nLanguage(lang)
        })
      }
      return resolve(setI18nLanguage(lang))
    }
    return resolve(lang)
  })
}

export function i18nRender(key) {
  return i18n.t(key)
}

export default i18n